<template>
  <base-breadcrumb>
    <a-spin
      :spinning="spinning&&!projectInfo.projectId"
      style="margin: 0"
    >
      <a-card>
        <a-tabs
          v-model="nextStep"
        >
          <a-tab-pane
            key="1"
            tab="基本信息"
          >
            <a-form-model
              ref="ruleForm"
              :model="form"
            >
              <a-row :gutter="24">
                <a-col
                  :span="16"
                >
                  <a-form-model-item
                    label="所属单位："
                    prop="projectId"
                    :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 17 } }"
                  >
                    <org-tree-select
                       is-need-auth
                       is-auto-select-first
                       check-strictly
                       disabled
                      v-model="form.projectId"
                      @select="selectOrg"
                       @getProjectInfo="getProjectInfo"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                 :span="8"
                >
                  <a-form-model-item
                    label="名称："
                    prop="name"
                    :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                    :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                  >
                    <BaseInput v-model="form.name" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col
                        :span="8"
                >
                  <a-form-model-item
                          label="项目业态："
                          prop="name"
                          :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                          :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                  >
                    <BaseInput v-model="projectInfo.projectFormatName" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col
                        :span="8"
                >
                  <a-form-model-item
                          label="项目设计管理类别："
                          prop="name"
                          :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                          :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                  >
                    <BaseInput v-model="projectInfo.designName" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col
                        :span="8"
                >
                  <a-form-model-item
                          label="合同额(万)（不含内部分包）："
                          prop="name"
                          :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                          :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                  >
                    <BaseInput v-model="ownerValue" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </a-tab-pane>
          <a-tab-pane
            key="2"
            tab="双优化立项计划表"
          >
            <div class="table-operator">
              <a-button
                v-if="btns"
                type="primary"
                @click="added(true)"
              >
                添加计划项
              </a-button>
              <ExcelImportButton
                      ref="excelImportButton"
                      :loading="loadingImport"
                      icon="import" button-text="导入" @handleSubmit="handleImport" />
              <ExportExcel
                      v-if="btns"
                      ref="exportExcel"
                      :export-list="exportList"
                      icon="download"
                      :file-name="'双优化立项计划表.xlsx'"
                      button-text="下载导入模板"
              />
            </div>
            <a-table
              row-key="id"
              :scroll="{x:true}"
              :data-source="dataSource"
              :columns="columns"
              bordered
              :pagination="false"
              :loading="loading.loadTable"
            >
              <span
                slot="description"
                slot-scope="text"
              >
                <ellipsis
                  :length="8"
                  tooltip
                >{{ text }}</ellipsis>
              </span>
              <span
                slot="serial"
                slot-scope="text, record, index"
              >{{ index + 1 }}</span>
              <!-- 操作 -->
              <span
                slot="operation"
                slot-scope="text, record"
              >
                <template>
                   <a @click="look(record)">查看</a>
                  <template v-if="!record.status || !record.isProject">
                     <a-divider type="vertical" />
                  <a @click="addSee(record, false)">编辑</a>
                  <a-divider type="vertical" />
                  <a-popconfirm
                    title="确定要删除?"
                    @confirm="() => addEdit(record)"
                  >
                    <a>删除</a>
                  </a-popconfirm>
                    </template>
                  <!-- <a @click="addEdit(record)">删除</a> -->
                </template>
              </span>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-card>

      <div class="tool-btns page-btn-right-top">
        <a-button
          v-if="nextStep == '2' && form.auditStatus"
          type="danger"
          @click="discard(form)"
        >
          删除草稿
        </a-button>
        <a-button
          v-if="nextStep == '2'"
          type="primary"
          @click="back"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="nextStep == '1'"
          type="primary"
          @click="next"
        >
          下一步
        </a-button>
        <a-button
          v-else
          type="primary"
          @click="onSubmit('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="back"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
    <EditFrom
      v-if="visible"
      :visible="true"
      :model="transmitList"
      :project-id="form.projectId"
      :dept-id="deptId"
      :view="view"
      :projectInfo="projectInfo"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>

<script>
import EditFrom from './EditFrom.vue'
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import ExcelImportButton from '@/components/ExcelImportButton'
import { addPlan, detailed, eliminatePlan, modifyPlan, rowPlan, rewritePlan } from '@/api/technical/optimizationPlan'
const columns = [
    {
        title: '序号',
        width: '65px',
        scopedSlots: { customRender: 'serial' },
    },
    {
        title: '双优化名称',
        dataIndex: 'name',
    },
    {
        title: '双优化分类',
        dataIndex: 'categoryName',
    },
    {
        title: '内容概述',
        dataIndex: 'content',
    },
    {
        title: '计划实施时间',
        dataIndex: 'startTime',
      width: 120,
    },
    {
        title: '提出人',
        dataIndex: 'proposer',
    },
    {
        title: '拟实施人',
        dataIndex: 'implement',
    },
    {
        title: '策划效益(万)',
        dataIndex: 'benefit',
      width: 120,
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: '160px',
        scopedSlots: { customRender: 'operation' },
    },
]
export default {
    name:'a'+Date.now(),    components: {
        EditFrom,
    ExportExcel,
    ExcelImportButton
    },
  computed: {
    exportList() {
      return  [
        {
          columns: [
            {
              title: '双优化名称',
              dataIndex: 'name',
            },
            {
              title: '专业类别',
              dataIndex: 'categoryName',
            },
            {
              title: '内容概述',
              dataIndex: 'content',
            },
          ],
          datas: [{}]
        }
        ]
    },
    ownerValue() {
      if(this.form.isSubProject) {
        // 是内部分包项目
        return this.projectInfo.contractAmount
      } else {
        if( this.projectInfo.ownerContractValue) {
          // 不是内部分包项目 contractAmount // 其内部分包项目的“分包合同额”
          return (parseInt((this.projectInfo.ownerContractValue*100).toFixed()) -  parseInt((this.form.subContractAmount*100).toFixed()))/100
        }
      }
      return ''
    }
  },
   async mounted() {
     this.spinning = true
     this.processConfig = await this.$getConfigFn('double-optimizing_cancellation_implement')
        this.btn = this.$route.query.btn
        this.btns = this.$route.query.btns
        this.form.id = this.$route.query.id
        this.dataList()
          //获取通过获取流程配置值
    },
    data() {
        this.columns = columns
        return {
            view: false,
            deptId: '', // 项目部ID
            loading: {
                loadTable: false,
            },
            id: '',
            nextStep: '1',
            spinning: false,
            btns: null,
            btn: null,
            visible: false,
            transmitList: {},
            dataSource: [],
            form: {
               isSubProject: false,
                branchComId: '',
                projectId: '',
                name: '',
            },
            isShow: '',
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null,
            projectInfo: {},
            loadingImport: false
        }
    },
    methods: {
      next() {
        this.nextStep = '2'
      },
      async handleImport(val) {
        if(val.length == 0) {
          this.$message.warning('请填写内容')
          return
        }
        this.loadingImport = true
        let professionalTypeEmus = [
          {
          key: '建筑',
          value: 'CIVIL'
         },
          {
            key: '机电',
            value: 'ELECTRICAL'
          },
          {
            key: '结构',
            value: 'STRUCTURE'
          },
          {
            key: '市政景观',
            value: 'LANDSCAPE'
          }
          ]
        let flag = true
        let arr = []
        for(let prop in val[0]) {
          if(prop !== '双优化名称'&&prop !== '内容概述'&&prop !== '专业类别'){
            this.$message.warning('请导入正确的模板')
            this.loadingImport = false
            return
          }
        }

        val.forEach((item, i)=>{
          let obj = {}
          for(let prop in item) {
            if(prop === '双优化名称') {
              obj.name = item[prop]
            } else if(prop === '内容概述') {
              obj.content = item[prop]
            } else {
             const o = professionalTypeEmus.find(ele => ele.key === item[prop])
              if(!o) {
                this.$message.warning(`第${i+1}行专业类别不正确`)
                flag = false
                this.loadingImport = false
                break
              } else {
                obj.professionalType = o.value
              }
            }
          }
          arr.push(obj)
        })
        if(flag) {
          try {
            for(let i=0,len=arr.length;i<len; i++) {
              let obj = {
                ...arr[i],
                basicId: this.form.id,
              }
              await rowPlan(obj)
            }
            await  this.dataList(true, true)
          } catch (e) {
            this.loadingImport = false
          }
        }
      },
      selectOrg(val) {
        if (val && val.length > 2) {
          this.form.branchComId = val[val.length - 2].orgId
          this.form.projectName = val[val.length - 1].projectName
          const year = new Date().getFullYear()
          this.form.name = this.form.projectName ? `${this.form.projectName}${year}年双优化立项计划` : ''
        }
      },
      getProjectInfo(info) {
        this.spinning = false
        this.deptId = info.projectDeptOrgId
        if(info.projectFormatName?.length) {
          info.projectFormatName = info.projectFormatName.join(",")
        }
        if(info.innerPackageCode === 0) {
          info.ownerValue = +info.ownerContractValue - info.contractAmount
        } else {
          info.ownerValue = info.contractValue
        }
        this.projectInfo = info
      },
        handleProChanged() {
            const projectName = this.$refs.selectProject.getValueName(this.form.projectId)
            const year = new Date().getFullYear()

            this.form.name = projectName ? `${projectName}${year}年双优化立项计划` : ''
        },
        dataList(editForm = true, isImport = false) {
            if (this.form.id) {
                if (this.loading.loadTable) return
                this.loading.loadTable = true
                detailed(this.form.id)
                    .then((res) => {
                        this.loading.loadTable = false
                        this.spinning = false
                        if (res.code === 200 || res.data.code === 200) {
                          res.data.doubleOptimizationTypeVO&&res.data.doubleOptimizationTypeVO.forEach(w=>{
                            if(w.status) {
                              w.statusName = { PAST: '立项审批通过', REJECTED: '立项审批不通过', DRAFT: '待立项', SUBMITTED: '立项审核中' }[
                                      w.status
                                      ]
                            } else {
                              w.statusName = '立项待提交'
                            }
                          })
                            this.dataSource = res.data.doubleOptimizationTypeVO
                            if (editForm) {
                                this.form = { ...res.data }
                            }
                            if(isImport) {
                              this.$message.success('导入成功！请在本页面各行点击“编辑”完善计划项信息。')
                              this.loadingImport = false
                            }
                        } else {
                            this.$message.info('获取数据失败')
                        }
                    })
                    .catch(() => {
                        this.loading.loadTable = false
                    })
            }
        },
        // 传值控制弹窗开关
        handleCancel() {
            this.visible = false
        },
        handleOk(e) {
            e.implementId = e.implementId?.join(',')
            e.proposerId = e.proposerId?.join(',')
            if (this.isShow === true) {
                //  ids: data.join(','),
                console.log(e)

                let obj = {
                    ...e,
                    basicId: this.form.id,
                }
                rowPlan(obj).then((res) => {
                    console.log(res)
                    if (res.data.code === 200 || res.code === 200) {
                        this.dataList(true)
                      this.visible = false
                        this.$message.success('添加成功')
                    }
                })
            } else {
                let obj = {
                    ...e,
                    id: this.transmitList.id,
                    basicId: this.form.id,
                }
                rewritePlan(obj).then((res) => {
                    if (res.code === 200 || res.data.code === 200) {
                        this.dataList(true)
                      this.visible = false
                        this.$message.success('成功')
                    }
                })
            }
        },
        // 新增计划项目
        added(e) {
            this.view = false
            this.transmitList = {}
            this.visible = true
            this.isShow = e
        },
        //删除行
        addEdit(e) {
            eliminatePlan({
                id: e.id,
            }).then((res) => {
                if (res.code == 200 || res.data.code === 200) {
                    this.$message.success('删除成功')
                    this.dataList(true)
                } else {
                    this.$message.error('删除失败')
                }
            })
        },
      look(a) {
        this.view = true
        if (!Array.isArray(a.implementId)) {
          a.implementId = a.implementId?.split(',')
          a.proposerId = a.proposerId?.split(',')
        }
        this.transmitList = a
        this.visible = true
      },
        // 编辑
        addSee(a, b) {
          this.view = false
            console.log("a",a)
            if (!Array.isArray(a.implementId)) {
                a.implementId = a.implementId?.split(',')
                a.proposerId = a.proposerId?.split(',')
            }

            console.log(a)
            this.transmitList = a
            this.visible = true
            this.isShow = b
        },
        // 关闭
        back() {
            this.$multiTab.close(this.$route.fullpath)
        },
        discard(record) {
            let _this = this
            this.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    return eliminate({ id: record.id }).then((res) => {
                        _this.$message.success('删除成功')
                        _this.back() // 刷新
                    })
                },
                onCancel() {},
            })
        },
        // 基本信息保存
        onSubmit(status) {
            this.setProcessConfig = null;
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if(this.spinning) return
                    this.spinning = true
                    this.submitApprovalConfirm(status =='SUBMITTED' ? this.processConfig:6, (flag)=>{
                      if(!flag) {
                        this.spinning = false
                        return
                      }
                      if(this.form.doubleOptimizationTypeVO.length) {
                        let prop = ['name', 'startTime', 'category', 'detailedCategory', 'designStageId',
                          'optimizeStageId', 'projectTypeId', 'partId', 'isNew', 'proposerId', 'implementId',
                        'benefit', 'professionalType', 'content']
                        let flag = true, row=0
                        for(let i = 0; i < this.form.doubleOptimizationTypeVO.length; i++) {
                          const ele = this.form.doubleOptimizationTypeVO[i]
                          if(!ele.status) {
                          for(let j = 0; j < prop.length; j++) {
                            if (ele.category === 222) {
                              console.log(prop[j], 'prop[j]')
                              if (ele[prop[j]] == null && prop[j] !== 'designStageId' && prop[j] !== 'optimizeStageId') {
                                flag = false
                                row = i
                                break
                              }
                            } else {
                              if (ele[prop[j]] == null) {
                                console.log(prop[j], 'prop[j]')
                                flag = false
                                row = i
                                break
                              }
                            }
                          }
                          }
                          if(!flag) {
                            break
                          }
                        }
                        if(!flag) {
                          this.spinning = false
                          this.$message.warning('计划项信息不完整')
                          return
                        }
                      }
                    if (this.form.id) {
                        let obj = {
                            ...this.form,
                            id: this.form.id,
                            status,
                        }
                        modifyPlan(obj).then((res) => {
                            this.spinning = false
                            if (res.code === 200 || res.data.code === 200) {
                                this.$message.success('成功')
                                if (this.nextStep == '2') {
                                    if(status =='SUBMITTED') {
                                        //提交时，返回id
                                        this.businessId = res.data.id || this.form.id;
                                        this.setProcessConfig = this.processConfig;
                                        return
                                        }else{
                                    this.back()
                                    }
                                } else {
                                    this.nextStep = '2'
                                }
                            } else {
                                this.$message.error('失败')
                            }
                        }).catch(() => {
                            this.spinning = false
                        })
                    } else {
                        addPlan({ ...this.form, status }).then((res) => {
                            this.spinning = false
                            if (res.code === 200 || res.data.code === 200) {
                                this.$message.success('成功')
                                this.form.id = res.data.id || this.form.id
                                this.dataList(true)
                                 if(status =='SUBMITTED') {
                                    //提交时，返回id
                                    this.businessId = res.data.id;
                                    this.setProcessConfig = this.processConfig;
                                    return
                                  }
                                this.nextStep = '2'
                            } else {
                                this.$message.error('失败')
                            }
                        }).catch(() => {
                            this.spinning = false
                        })
                    }
                    })
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                }
            })
        },
    },
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.ant-tabs {
    min-height: 250px;
}
</style>
